package c_observer.b_design_pattern;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wug on 2016/6/16 0016.
 */
public class SubjectCar implements Subject {
    private List<Observer> observerList;

    /**
     * 燃油量
     */
    private int oilmass;
    /**
     * 汽车速度
     */
    private int speed;
    /**
     * 维持这个速度的时间
     */
    private int remainTime;

    public SubjectCar() {
        this.observerList = new ArrayList<>();
        this.oilmass = 60000;
        this.speed = 0;
    }

    @Override
    public void registerObserver(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observerList) {
            observer.update(this);
        }
    }

    private void setSpeed() {
        speed = (int)(Math.random()*100);
    }

    private void setRemainTime() {
        /**
         * 假设维持车速为5分钟以内的随机数
         */
        remainTime = (int)(Math.random()*300);
    }


    public int getSpeed() {
        return speed;
//        System.out.println("当前车速："+ speed +"km/h");
    }

    public int getRemainTime() {
        return remainTime;
//        System.out.println("维持该车速：" + remainTime +"s");
    }

    public int getRemainOil() {
        /**
         * 假设百公里油耗10L
         */
        oilmass -= 10000 * speed * remainTime/3600/100;
        return oilmass;
       /* System.out.println("剩余燃油：" + oilmass + "ml");*/
    }

    public void carController() {
        setSpeed();
        setRemainTime();
        notifyObservers();
    }
}
